package com.module.recall.manager;

import java.sql.Connection;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import base.dao.GenericHibernateDao;
import base.manager.GenericHibernateManager;

import com.module.antiFake.vo.AntiFakeScanHistory;
import com.module.organization.dao.OrganizationDao;
import com.module.organization.vo.EntBind;
import com.module.recall.dao.AppAttrDao;
import com.module.recall.dao.FirstCodeDao;
import com.module.recall.util.AntiFakeBeanUtil;
import com.module.recall.vo.TagCode;

public class AntiFakeProductCodeManager extends
		GenericHibernateManager<AntiFakeScanHistory, Long> {
	private static AntiFakeProductCodeManager service;

	@Override
	public GenericHibernateDao<AntiFakeScanHistory, Long> getDao() {
		return null;
	}

	public synchronized static AntiFakeProductCodeManager getInstance() {
		if (service == null) {
			service = new AntiFakeProductCodeManager();
		}
		return service;
	}

	/**
	 * 码dao
	 */
	private FirstCodeDao firstCodeDao = FirstCodeDao.getInstance();
	/**
	 * 码应用属性dao
	 */

	/**
	 * 组织dao
	 */
	private OrganizationDao organizationDao = OrganizationDao.getInstance();
	private AppAttrDao appAttrDao = AppAttrDao.getInstance();

	public AntiFakeScanHistory searchCodeInfoBatchNo(
			AntiFakeScanHistory antiFakeScanHistory) throws Exception {
		Session session = this.getSession();
		Transaction tx = session.beginTransaction();
		Connection conn = session.connection();
		try {
			// 读取码相关信息;
			TagCode tagCode = firstCodeDao.selectCodeInfo(session,
					antiFakeScanHistory.getCodeInfo());
			// 把码相关信息存放到antiFakeScanhistory对象中;
			setCodeInfoToScanHistory(antiFakeScanHistory, tagCode);
			// 读取码对应组织应用
			List<EntBind> appList = organizationDao.getOrgCurApp(session,
					tagCode.getOrgId());
			//根据OrgId查询OrgName，添加在antiFakeScanHistory中
			String orgName = organizationDao.getOrgNameById(session,
					tagCode.getOrgId());
			antiFakeScanHistory.setOrgName(orgName);
			// 读取码绑定相应信息;
			AntiFakeBeanUtil antiFakeBeanUtil = appAttrDao.findAttrsByCode(
					conn, antiFakeScanHistory, appList);

		} catch (Exception e) {
			tx.rollback();
			throw e;
		} finally {
			this.closeSession();
		}
		return antiFakeScanHistory;
	}

	/**
	 * 把码相关信息存放到antiFakeScanhistory对象中
	 * 
	 * @param antiFakeScanHistory
	 * @param tagCode
	 */
	private void setCodeInfoToScanHistory(
			AntiFakeScanHistory antiFakeScanHistory, TagCode tagCode) {
		antiFakeScanHistory.setRollNum(tagCode.getRollNum());
		antiFakeScanHistory.setSequenceNum(tagCode.getSequenceNum());
		antiFakeScanHistory.setType(tagCode.getType().shortValue());
		antiFakeScanHistory.setFirstCodeInfo(tagCode.getFirstCodeInfo());
		antiFakeScanHistory.setLayerNum(tagCode.getTypeNum().shortValue());
		antiFakeScanHistory.setOrgid(tagCode.getOrgId());
	}
}
